import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/public-lessons'
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue')
    },
    {
      path: '/lesson-plans',
      name: 'lessonPlans',
      component: () => import('../views/LessonPlansView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/public-lessons',
      name: 'publicLessonPlans',
      component: () => import('../views/PublicLessonPlansView.vue')
    },
    {
      path: '/lesson-plans/create',
      name: 'createLessonPlan',
      component: () => import('../views/EditLessonPlanView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/lesson-plans/:id',
      name: 'lessonPlanDetail',
      component: () => import('../views/LessonPlanDetailView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/lesson-plans/:id/edit',
      name: 'editLessonPlan',
      component: () => import('../views/EditLessonPlanView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/forgot-password',
      name: 'forgotPassword',
      component: () => import('../views/ForgotPasswordView.vue')
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/ProfileView.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果有token但没有用户信息，尝试获取用户信息
  if (authStore.token && !authStore.user) {
    try {
      await authStore.fetchCurrentUser()
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 清除无效token
      authStore.setToken(null)
      authStore.setUser(null)
    }
  }
  
  // 需要认证的路由
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else if ((to.path === '/login' || to.path === '/register') && authStore.isAuthenticated) {
    // 已登录用户访问登录/注册页面时重定向到公开教案页或目标页面
    const redirect = to.query.redirect as string || '/public-lessons'
    next(redirect)
  } else {
    next()
  }
})

export default router